package com.atguigu.aliyunvod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.aliyunvod.service.VodService;
import com.atguigu.aliyunvod.util.ConstantVodUtils;
import com.atguigu.aliyunvod.util.InitVodClient;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping(value = "/eduvod/video")
@Api(description = "阿里云视频上传管理")
public class VodController {

    @Autowired
    VodService vodService;

    @ApiOperation("//获取前端上传文件，通过流式上传到阿里云")
    @PostMapping(value = "uploadAlyiVideo")
    public R uploadAlyiVideo(MultipartFile file) {

        String VideoId = vodService.uploadVIdeo(file);

        return R.ok().data("VideoId", VideoId);

    }

    @ApiOperation("//调用阿里云提供的SDK，根据视频ID删除阿里云视频")
    @DeleteMapping("{videoId}")
    public R removeVideo(@ApiParam(name = "videoId", value = "云端视频id", required = true)
                         @PathVariable String videoId) {

        R r = vodService.removeVideo(videoId);
        return r;

    }

    @ApiOperation("//调用阿里云提供的SDK，根据视频ID “批量” 删除阿里云视频")
    @DeleteMapping("deleteBatch")
    public R removeVideoList(@RequestParam List<String> videoIdList) {

        vodService.removeVideoList(videoIdList);
        return R.ok();
    }

    //根据视频id获得视频凭证
    @ApiOperation("根据视频id获得视频凭证")
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {

        try {
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request对象中设置视频id
            request.setVideoId(id);

            //调用方法获得凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth", playAuth);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"视频playAuth获取失败");
        }

    }

}
